<script setup>
import { Edit, Delete } from "@element-plus/icons-vue";
import { onMounted, ref } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { getCategoryAPI, addCategoryAPI, updateCategoryAPI, deleteCategoryAPI } from "@/api/category";
import { useUserStore } from "@/stores/useUserStore";

// 创建实例
const userStore = useUserStore();

// 获取当前账户分类数据
const categorys = ref();
const getCategorys = async () => {
  const res = await getCategoryAPI(userStore.account.id);
  if (res.code === 0) return (categorys.value = res.data);
  return ElMessage({ type: "error", message: res.message });
};

//控制添加分类弹窗
const dialogVisible = ref(false);
// 设置标题
const title = ref("添加分类");

//添加分类数据模型
const categoryModel = ref({
  id: "",
  categoryName: "",
  categoryAlias: "",
});
//添加分类表单校验
const rules = {
  categoryName: [{ required: true, message: "请输入分类名称", trigger: "blur" }],
  categoryAlias: [{ required: true, message: "请输入分类别名", trigger: "blur" }],
};
const fromRef = ref();
// 添加分类
const addCategory = async formEl => {
  if (!formEl) return;
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      if (categoryModel.value.id === "") {
        const res = await addCategoryAPI(categoryModel.value);
        stateCategory(res, "添加成功");
      } else {
        const res = await updateCategoryAPI(categoryModel.value);
        stateCategory(res, "修改成功");
      }
    } else {
      for (const key in fields) {
        ElMessage({ type: "error", message: fields[key][0].message });
      }
    }
  });
};

// 修改分类
const updateCategory = async row => {
  title.value = "修改分类";
  categoryModel.value.id = row.id;
  categoryModel.value.categoryName = row.categoryName;
  categoryModel.value.categoryAlias = row.categoryAlias;
  dialogVisible.value = true;
};
// 公共方法
const stateCategory = (res, message) => {
  if (res.code === 0) {
    dialogVisible.value = false;
    ElMessage({ type: "success", message });
    clearCategory();
    return getCategorys();
  }
  return ElMessage({ type: "error", message: res.message });
};

// 删除分类
const deleteCategory = row => {
  ElMessageBox.confirm("你确认删除该分类信息吗？", "警告", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      //用户点击了确认
      const res = await deleteCategoryAPI(row.id);
      if (res.code === 0) {
        ElMessage({ type: "success", message: "删除成功" });
        return getCategorys();
      }
      return ElMessage({ type: "error", message: res.message });
    })
    .catch(() => {
      //用户点击了取消
      ElMessage({ message: "取消删除" });
    });
};

// 判断是否放弃更改
const handleClose = done => {
  if (!categoryModel.value.categoryName && !categoryModel.value.categoryAlias) return (dialogVisible.value = false);
  const str = categoryModel.value.id ? "修改" : "添加";
  ElMessageBox.confirm(`是否放弃当前${str}?`)
    .then(() => {
      done();
      getCategorys();
      clearCategory();
      return ElMessage({ message: `已放弃${str}` });
    })
    .catch(() => {});
};

const clearCategory = () => {
  dialogVisible.value = false;
  categoryModel.value.id = "";
  categoryModel.value.categoryName = "";
  categoryModel.value.categoryAlias = "";
};

onMounted(() => {
  getCategorys();
});
</script>
<template>
  <el-card class="page-container" v-if="categorys">
    <template #header>
      <div class="header">
        <span>文章分类</span>
        <div class="extra">
          <el-button type="primary" @click="dialogVisible = true">添加分类</el-button>
        </div>
      </div>
    </template>
    <el-table :data="categorys" style="width: 100%">
      <el-table-column label="序号" width="100" type="index"></el-table-column>
      <el-table-column label="分类名称" prop="categoryName"></el-table-column>
      <el-table-column label="分类别名" prop="categoryAlias"></el-table-column>
      <el-table-column label="操作" width="100">
        <template #default="{ row }">
          <el-button :icon="Edit" circle plain type="primary" @click="updateCategory(row)"></el-button>
          <el-button :icon="Delete" circle plain type="danger" @click="deleteCategory(row)"></el-button>
        </template>
      </el-table-column>
      <template #empty>
        <el-empty description="没有数据" />
      </template>
    </el-table>
  </el-card>
  <!-- 添加分类弹窗 -->
  <el-dialog v-model="dialogVisible" :title="title" width="30%" :before-close="handleClose">
    <el-form :model="categoryModel" :rules="rules" label-width="100px" style="padding-right: 30px" ref="fromRef">
      <el-form-item label="分类名称" prop="categoryName">
        <el-input v-model="categoryModel.categoryName" minlength="1" maxlength="10"></el-input>
      </el-form-item>
      <el-form-item label="分类别名" prop="categoryAlias">
        <el-input v-model="categoryModel.categoryAlias" minlength="1" maxlength="15"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="clearCategory">取消</el-button>
        <el-button type="primary" @click="addCategory(fromRef)">确认</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<style lang="scss" scoped>
.page-container {
  min-height: 100%;
  box-sizing: border-box;

  .header {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
}
</style>
